package com.javasm.Service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasm.Service.RoleFunctionService;
import com.javasm.Service.UserRoleService;
import com.javasm.Service.UserService;
import com.javasm.entity.RoleFunction;
import com.javasm.entity.User;
import com.javasm.entity.UserRole;
import com.javasm.mapper.RoleFunctionMapper;
import com.javasm.mapper.UserMapper;
import com.javasm.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleFunctionService roleFunctionService;

    public User getByUserName(String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public User getByPhone(String phone) {
        QueryWrapper<User> queryWrapper=new QueryWrapper();
        queryWrapper.eq("phone",phone);
        return baseMapper.selectOne(queryWrapper);
    }

    public List<String> getFunctions(Integer userId){
        QueryWrapper<UserRole> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<UserRole> userRoles = userRoleService.list(queryWrapper);
        List<String> roleCodes = userRoles.stream().map(UserRole::getRoleCode).collect(Collectors.toList());
        QueryWrapper<RoleFunction> roleFunctionQueryWrapper=new QueryWrapper<>();
        roleFunctionQueryWrapper.in("role_code",roleCodes);
        List<RoleFunction> roleFunctions = roleFunctionService.list(roleFunctionQueryWrapper);
        return roleFunctions.stream().map(RoleFunction::getFunctionCode).collect(Collectors.toList());
    }
}
